param (
  [string]$InputFolder = "", # 输入目录
  [string]$OutputFolder = "" # 输出目录
)

# 检查 FFmpeg 是否安装
if (-not (Get-Command ffmpeg -ErrorAction SilentlyContinue) -or -not (Get-Command ffprobe -ErrorAction SilentlyContinue)) {
  Write-Host "❌ 未检测到 FFmpeg, 请先安装后再运行！喵~ (╥﹏╥)" -ForegroundColor Red
  exit
}

# 确保输出目录存在
if (!(Test-Path $OutputFolder)) {
  New-Item -ItemType Directory -Path $OutputFolder | Out-Null
}

# 检查是否支持 NVIDIA NVENC 硬件加速
$NVENC_Support = ffmpeg -encoders 2>$null | Select-String "h264_nvenc"
$UseGPU = $null -ne $NVENC_Support

if (-not $UseGPU) {
  Write-Host "⚠️ 当前设备不支持 NVIDIA 硬件加速，使用 CPU 进行转码..."
}
else {
  Write-Host "😊 当前设备支持 NVIDIA 硬件加速"
}
# 遍历输入目录下的所有文件
Get-ChildItem -Path $InputFolder -File | ForEach-Object {
  $InputFile = $_.FullName
  $FileName = [System.IO.Path]::GetFileNameWithoutExtension($_.Name)
  $VideoOutputDir = "$OutputFolder\$FileName"

  # 确保每个视频的输出目录存在
  if (!(Test-Path $VideoOutputDir)) {
    New-Item -ItemType Directory -Path $VideoOutputDir | Out-Null
  }

  # 获取视频分辨率（高度）
  $Resolution = & ffprobe -v error -select_streams v:0 -show_entries stream=height -of csv=p=0 "$InputFile"
  $Resolution = [int]$Resolution

  # 获取原始视频比特率（转换为 kbps）
  $originalBitrate = (& ffprobe -v error -select_streams v:0 -show_entries format=bit_rate -of csv=p=0 "$InputFile")
  $originalBitrate = [math]::Floor([int]$originalBitrate / 1000)

  # 获取原始音频比特率（转换为 kbps）
  $originalAudioBitrate = (& ffprobe -v error -select_streams a:0 -show_entries stream=bit_rate -of csv=p=0 "$InputFile")
  $originalAudioBitrate = [math]::Floor([int]$originalAudioBitrate / 1000)

  $bitrates = @{
    1080 = @{ bitrate = 5000; scale = "1920:1080" }
    720  = @{ bitrate = 2500; scale = "1280:720" }
    360  = @{ bitrate = 800; scale = "640:360" }
  }

  # 获取可以转换的分辨率
  $streams = @()
  foreach ($res in $bitrates.Keys) {
    if ($Resolution -ge [int]($bitrates[$res]['scale'] -split ":")[1]) {
      $streams += $res
    }
  }

  if ($streams.Count -eq 0) {
    $streams += 360
  }

  $playlistFiles = @()

  foreach ($res in $streams) {
    $outFile = "$VideoOutputDir\stream_${res}.m3u8"
    $playlistFiles += "stream_${res}.m3u8"

    # 计算最终比特率（取最小值）
    $targetBitrate = [math]::Min($originalBitrate, $bitrates[$res]['bitrate'])
    $targetAudioBitrate = [math]::Min($originalAudioBitrate, 320) # 限制最高 320kbps

    ffmpeg -i "$InputFile" `
      -vf "scale=$($bitrates[$res]['scale'])" `
      -c:v ($UseGPU ? "h264_nvenc" : "libx264") `
      -preset ($UseGPU ? "fast" : "fast") `
      -b:v "$($targetBitrate)k" `
      -c:a aac -b:a "$($targetAudioBitrate)k" `
      -hls_time 4 -hls_list_size 0 `
      -hls_segment_filename "$VideoOutputDir/stream_${res}_%03d.ts" `
      -f hls "$outFile"
  }

  # 生成 master.m3u8 播放列表
  $MasterPlaylist = "$VideoOutputDir\master.m3u8"
  $PlaylistContent = "#EXTM3U`n"

  foreach ($res in $streams) {
    $PlaylistContent += "#EXT-X-STREAM-INF:BANDWIDTH=$($bitrates[$res]['bitrate'] * 1000),RESOLUTION=$($bitrates[$res]['scale'])`n"
    $PlaylistContent += "stream_${res}.m3u8`n"
  }

  Set-Content -Path $MasterPlaylist -Value $PlaylistContent
}

Write-Host "✅ 批量 HLS 转码完成！喵~ (ฅ^･ω･^ฅ)"